<template>
    <div class="main el-box-init el-bkgd-white el-pd-20">
        <!-- 表格过滤 -->
        <el-form :inline="true" class="table-filter el-box-init el-bkgd-white">
            <el-form-item label="关键词" class="el-mg-r-30">
                <el-input v-model="keywor" clearable placeholder="请输入分类名" />
            </el-form-item>

            <el-form-item>
                <el-button type="success" round @click="onSearch">
                    <el-icon class="table-icon"><search /></el-icon>
                    查询
                </el-button>
                <el-button type="warning" round @click="onReset">
                    <el-icon class="table-icon"><refresh /></el-icon>
                    重置
                </el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <common-table
            :table="table"
            @handleSelectionChange="handleSelectionChange"
            @handleSizeChange="handleSizeChange"
            @handleCurrentChange="handleCurrentChange"
            ref="common-table"
        ></common-table>

        <dialog-add-or-update ref="addOrUpdate" />
    </div>
</template>

<script>
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';
import { mixins } from '@/global/utils/mixins';
import { adminClassify as Api } from 'api';
import DialogAddOrUpdate from './add-or-update.vue';

export default {
    mixins: [mixins],
    components: {
        DialogAddOrUpdate
    },
    setup() {
        const { proxy } = getCurrentInstance();
        let allDelBtnVisible = ref(false); // 表格全选
        let selectIds = []; // 表格选择的id
        // 搜索
        let search = reactive({
            keywor: ''
        });
        // 表格
        let table = reactive({
            // 表格列配置
            loading: false, // 加载动画(可选)
            selection: true, // 开启全选<增加勾选列>(可选)
            sort: false, // 开启输入排序<增加输入排序列>(可选)
            stripe: true, // 是否为斑马纹 table(可选)
            border: true, // 是否带有纵向边框(可选)
            fit: true, // 列的宽度是否自撑开(可选,默认true)
            showHead: true, // 是否显示表头(可选,默认true)
            highlight: false, // 是否要高亮当前行(可选,默认false)
            size: 'default', // Table 的尺寸(可选,默认default)<值：large / default /small>
            // 表格列(必选)
            col: [
                // prop(必选),
                // label(必选),
                // width(可选),
                // align(可选)<值：left / center / right>,
                // type(可选)<值：tag / popover / date><type="tag"时需要使用formatter方法>,
                // formatter(可选)<选择该项时 type="tag"显示标签样式 >
                { prop: 'title', label: '分类', width: 120, align: 'center' },
                { prop: 'desc', label: '描述' },
                {
                    prop: 'support',
                    label: '是否推荐',
                    width: 100,
                    align: 'center',
                    type: 'tag',
                    formatter: (row, type) => {
                        return type
                            ? row.support == 1
                                ? ''
                                : 'warning'
                            : row.support == 1
                            ? '是'
                            : '否';
                    }
                },
                { prop: 'issuer_name', label: '创建人', width: 100, align: 'center' },
                { prop: 'created_time', label: '创建时间', width: 180, type: 'date' }
            ],
            // 数据列表(必选)
            list: [],
            // 头部操作按钮(可选)
            headBtn: [
                {
                    type: 'primary',
                    icon: 'add',
                    label: '新增',
                    auth: proxy.isAuth('BLOG_CLASSIFY_ADD'),
                    click: () => onAddOrUpdate()
                },
                {
                    type: 'warning',
                    icon: 'refresh',
                    label: '更新排序',
                    auth: proxy.isAuth('BLOG_CLASSIFY_SORT'),
                    click: () => onUpdateSort()
                },
                {
                    type: 'danger',
                    icon: 'del',
                    label: '批量删除',
                    btnVisible: true,
                    auth: proxy.isAuth('BLOG_CLASSIFY_DEL'),
                    click: () => onDel()
                }
            ],
            // 表格列操作按钮(可选)
            colBtn: {
                width: proxy.$defaultActionWidth, // 操作列宽(可选)
                data: [
                    {
                        type: 'primary',
                        icon: 'edit',
                        label: '编辑',
                        auth: proxy.isAuth('BLOG_CLASSIFY_UPDATE'),
                        click: (row) => onAddOrUpdate(row.id)
                    },
                    {
                        type: 'danger',
                        icon: 'del',
                        label: '删除',
                        auth: proxy.isAuth('BLOG_CLASSIFY_DEL'),
                        click: (row) => onDel(row.id)
                    }
                ]
            },
            // 分页(可选)
            paging: {
                currentPage: proxy.$config.pagination.currentPage, // 当前第几页(必选)
                pageSize: proxy.$config.pagination.pageSize, // 每页多少条(必选)
                pageSizes: proxy.$config.pagination.pageSizes, // 每页显示个数下拉选择器的选项设置(必选)
                layout: proxy.$config.pagination.layout, // 组件布局，子组件名用逗号分隔(必选)
                total: 0 // 总条数(必选)
            }
        });

        // 获取列表
        const getList = async () => {
            const { code, data } = await proxy.$http.get(Api.getList, {
                params: {
                    keywor: search.keywor,
                    page: table.paging.currentPage, //查询第几页
                    per_page: table.paging.pageSize //每页多少条数据
                }
            });

            if (code === 200) {
                table.list = data.list;
                table.paging.total = data.total;
                // 关闭提示
                table.loading = false;
            }
        };
        getList().then(() => {
            proxy.rowDrop();
        });

        // 查询
        const onSearch = () => {
            table.loading = true;
            initTableSelectionIds();
        };
        // 重置
        const onReset = () => {
            search.keywor = '';
            onSearch();
        };
        // 新增、编辑
        const onAddOrUpdate = (id) => {
            proxy.$refs.addOrUpdate.id = id;
            proxy.$refs.addOrUpdate.visible = true; // 弹窗开关
        };
        // 排序
        const onUpdateSort = async () => {
            const sortList = table.list.map((item, index) => ({
                id: item.id,
                sort: index + (table.paging.currentPage - 1) * table.paging.pageSize
            }));

            const { code, msg, data } = await proxy.$http.post(Api.onUpdateSort, {
                sortList: JSON.stringify(sortList)
            });

            if (code == 200) {
                proxy.$msg.success(msg);

                // 初始化清除表格选中、刷新
                initTableSelectionIds();
            } else {
                proxy.$msg.error(msg ? msg : data);
            }
        };
        // 删除
        const onDel = async (id) => {
            if (!id) id = selectIds.map((item) => item.id).join(',');

            // 确认删除
            const confirm = await proxy.$msgBox.confirm({
                cancel: true
            });

            if (confirm) {
                const { code, data, msg } = await proxy.$http.delete(Api.del, {
                    data: { id }
                });

                if (code === 200) {
                    proxy.$msg.success(msg);
                    initTableSelectionIds();
                } else {
                    proxy.$msg.error(msg ? msg : data);
                }
            }
        };
        // 表格全选
        const handleSelectionChange = (rows) => {
            selectIds = rows;
            allDelBtnVisible.value = selectIds.length ? true : false;
            proxy.$store.commit('updateAllDelBtnVisible', allDelBtnVisible.value);
        };
        // 每页多少条
        const handleSizeChange = (val) => {
            table.loading = true;
            table.paging.pageSize = val;
            initTableSelectionIds();
        };
        // 当前页
        const handleCurrentChange = (val) => {
            table.loading = true;
            table.paging.currentPage = val;
            initTableSelectionIds();
        };
        // 初始化清楚表格选中、全选数组、表格刷新
        const initTableSelectionIds = () => {
            proxy.$refs['common-table'].$refs['tableRef'].clearSelection(); // 清除表格选择
            selectIds = [];
            getList();
        };

        return {
            ...toRefs(search),
            table,
            onSearch,
            onReset,
            handleSelectionChange,
            handleSizeChange,
            handleCurrentChange,
            initTableSelectionIds
        };
    }
};
</script>
